;; SCALA

(defun scala-home () (get-env "SCALA_HOME"))

(defun scalac (source &optional dest cp)
  "Compile SOURCE by using scala compiler. DEST is
the destination folder where the output classes
are to be stored. CP is the class path.

Example: (scalac \"c:/Temp/Test.scala\" \"c:/Temp\")"
  (interactive)
  (scala-launch 'java "*scalac*" 't ;; a readonly buffer
                "scala.tools.nsc.Main"
                nil nil
                "-classpath" (if (= 0 (length cp)) "." cp)
                "-d" (if (= 0 (length dest)) "." dest) source))



(defun scala (&optional script cp sysprops &rest args)
  "Run a scala program. If there's no SCRIPT,
a scala shell will be launched; otherwise the SCRIPT
would be executed. CP is the class path by which
the SCRIPT is found."
  (interactive "MScript: \nMClasspath: ")
  (let ((main-class "scala.tools.nsc.MainGenericRunner")
        (f1 (lambda (input) (= 0 (length input))))
        )
    (apply 'scala-launch (if (funcall f1 script) 'java-sh 'java)
           (if (funcall f1 script) "scala-interpreter"
             (concat "*" script "*"))
           't ;; a readonly buffer
           main-class nil sysprops
           "-cp" (if (funcall f1 cp) "." cp)
           (if (funcall f1 script) nil script) args)
    ))



(defun scala-jars ()
  (directory-files (concat-file-names (scala-home) "/lib") 't))

(defun scala-sysprops (&optional more)
  (let ((default (list (cons "scala.home" (scala-home))
                       (cons "env.emacs" "t")
                       "-Xmx256M" "-Xms128M")))
    (nconc default (if (listp more) more (cons more nil)))
    ))


(defun scala-launch (java-proc buffer-name buffer-readonly
                               main-class
                               ;; additional classpath for the main-class, for example,
                               ;; you may need the classpath to find main-class
                               ;; should be a list of string
                               &optional class-path 
                               sysprops
                               &rest args)
  "Launch a scala process. JAVA-PROC is a function symbol 
indicating the running mode, which has three options:
'java, 'java-sh and 'java-sync; BUFFER-NAME is the name
of the buffer in which the process is running; MAIN-CLASS is 
the scala class to be launched; ARGS are the arguments passed
to the MAIN-CLASS."
  (let ((default-jars (scala-jars)))
    (apply java-proc
           (list (cons 'p-name buffer-name)
                 '(p-pop . t) '(p-clear . t)
               (cons 'p-readonly buffer-readonly))
           main-class
           (if (listp class-path)
               (nconc class-path default-jars)
             (cons class-path default-jars))
           (scala-sysprops sysprops)
           args)))


(add-to-list 'exec-path (concat-file-names (scala-home) "/bin"))

(add-to-list 'load-path "~/site-lisp/scala")
(require 'scala-mode-auto)

